//------------------------------------------------------------------------------
// Copyright (c) 2008 www.dnaide.com
// Licensed under the MIT (MIT-LICENSE.txt)
// ajaxaide_uncompressed.js
//------------------------------------------------------------------------------
var ajaxAide = function (){};
jQuery.extend(ajaxAide, {
	
	//
	// Call a specific .NET method using AjaxPro.NET - function needs [AjaxPro.AjaxMethod] meta data
	// Requires 7.4.24.1 or above
	//
	// assemblyName = .NET assembly name, minus extension eg -".dll"
	// className = .NET class to use - must include full namespace
	// methodToCall = Name of  .NET method must have [AjaxPro.Method] before the declaration in .NET class
	// parametersToPass = QueryString of params (all values must be escaped)
	// jsCallbackFunction = Javascript callback function. Should take "response" as a parameter. Access the response
	// value by response.value
	//
	invokeDotNetMethod: function(assemblyName, className, methodToCall, parametersToPass, jsCallbackFunction){
		if (typeof methodToCall == "undefined" || typeof className == "undefined" || typeof assemblyName == "undefined"){
			return;s
		}
		
		var jsonParameters = "";
		
		if (typeof parametersToPass != "undefined"){		
			// Convert the querystring into JSON for ajaxpro.net
			
			var arrParams = parametersToPass.split("&");
			for (var i=0; i<arrParams.length; i++){
				var arrParam = arrParams[i].split("=");
				if (arrParam.length == 2){
					var paramName = new String(arrParam[0]);
					var paramVal = new String(arrParam[1]);
					paramVal = unescape(paramVal);
					paramVal = paramVal.replace(/"/g, '\\"');
					paramVal = paramVal.replace(/'/g, "\\'");
					if (jsonParameters != ""){
						jsonParameters += ",";
					}
					jsonParameters += '"' + paramName + '":"' + paramVal + '"';
				}
			}
			if (jsonParameters != ""){
				jsonParameters = "{" + jsonParameters + "}";
			}
		}
		
		jQuery.ajax({
			type: "POST",  dataType: "json",
			url: appPath + "ajaxpro/" + className + "," + assemblyName + ".ashx",
			data: jsonParameters,
			beforeSend: function(xhr) {
				xhr.setRequestHeader("X-AjaxPro-Method", methodToCall);
			},
			success: function(response) {
				if (typeof jsCallbackFunction == "function"){
					jsCallbackFunction(response);
				}
			}
		});
	},
	
	
	//
	// Do an ajax "PostBack" of the form. Slightly less code than the .NET version :D
	// WebForm must implement System.Web.UI.ICallbackEventHandler.
	//
	// formId = id of the .NET form
	// eventArg = eventArg to pass back
	// additionalParametersToPass = QueryString of params (all values must be escaped)
	// jsCallbackFunction = Javascript callback function. Should take "response" as a parameter. Access the response
	// value by response.value
	// callBackControlId = the UniqueID of the control handling the callback. If this value is not supplied, it is 
	// assumed the page itself handles the callback. IMPORTANT. You must used the UniqueID of a control NOT the ClientID
	//
	raisePageCallBack: function(formId, eventArg, additionalParametersToPass, jsCallbackFunction, callBackControlId){
		
		if (typeof formId == "undefined" || formId == ""){
			throw("Missing formid");
		}
		var action = jQuery("#" + formId)[0].action;
		if (action == ""){
			action = " ";
		}
		if (typeof callBackControlId == "undefined" || callBackControlId == ""){
			callBackControlId = "__Page";
		}
		
		var parametersToPass = "__CALLBACKID=" + escape(callBackControlId) + "&__CALLBACKPARAM=" + escape(eventArg);
		
		// Get all input values and add to parametersToPass
		jQuery(":input", "#" + formId).each(function(){
			var val = new String();	
			var id = new String(this.id);
			var name = new String(this.name);
			var tagName = this.tagName.toLowerCase();
			var addField = false;
			if (tagName == "input") {
				var t = this.type;
				if ((t == "text" || t == "hidden" || t == "password" ||
						((t == "checkbox" || t == "radio") && this.checked))) {
						val = this.value;
						addField = true;
				}
			}
			else if (tagName == "select") {
				var selectCount = this.options.length;
				for (var j = 0; j < selectCount; j++) {
					var selectChild = this.options[j];
					if (selectChild.selected == true) {
						val = this.value;
						addField = true;
					}
				}
			}
			else if (tagName == "textarea") {
				val = this.value;
				addField = true;
			}
			
			if (addField){
				if (name == "") name = id;
				if (encodeURIComponent) {
					val = encodeURIComponent(val);
				}
				else {
					val = escape(parameter);
				}
				parametersToPass += "&" + name + "=" + val;
			}
		});
		
		if (typeof additionalParametersToPass != "undefined" || additionalParametersToPass != ""){
			parametersToPass += "&" + additionalParametersToPass;
		}
		
		jQuery.ajax({
			type: "POST",  dataType: "html",
			url: action,
			data: parametersToPass,
			success: function(response) {
				var responseVal = new String("");
				var responseError = new String("");
				var responseRaw = new String(response);
				
				//if (response.indexOf('System.Web.HttpWriter') > -1){
				//	alert('here');
				//}
			
				if (response.charAt(0) == "s") {
					responseVal = responseRaw.substring(1);
				}
				else if (response.charAt(0) == "e") {
					responseError = responseRaw.substring(1);
				}
				else {
					var separatorIndex = response.indexOf("|");
					if (separatorIndex != -1) {
						var validationFieldLength = parseInt(responseRaw.substring(0, separatorIndex));
						if (!isNaN(validationFieldLength)) {
							var validationFieldVal = 
								responseRaw.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
							if (validationFieldVal != "") {
								var validationFieldJObj = jQuery("#__EVENTVALIDATION", "#" + formId);
								if (validationFieldJObj.length > 0){
									var validationFieldObj = validationFieldJObj[0];
									validationFieldObj.value = validationFieldVal;
								}
							}
							responseVal = responseRaw.substring(separatorIndex + validationFieldLength + 1);
						}
						else{
							responseVal = responseRaw.substring(separatorIndex+1);
						}
					}
				}
			
				// Convert response to JavaScript object
				response = {value: responseVal, error: responseError};
				if (typeof jsCallbackFunction == "function"){
					jsCallbackFunction(response);
				}
			}
		});
		
		}

});
